/*
 * @Author: guoshouwang guoshouwang@qq.com
 * @Date: 2024-03-31 15:34:02
 * @LastEditors: guoshouwang guoshouwang@qq.com
 * @LastEditTime: 2024-04-28 17:58:35
 * @FilePath: \meta-planet-uni\business\router\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import uniCrazyRouter from "uni-crazy-router";
import {
  byUrlWorkCb,
  isTabbarPage,
} from "@/infrastructure/utils/is-tabbar-page.js";

var routes = ROUTES_MAP;

const reflashHomePage = async (to) => {
  if (to.url === "views/pages/meta/index" && uni.getStorageSync("cityID")) {
    console.log("路由拦截执行");
    await uni.$store.metaStore.getBlockListApi();
  }
};

export function setupRouter(app) {
  // 接收vue3的实例，并注册uni-crazy-router
  app.use(uniCrazyRouter);
}

uniCrazyRouter.beforeEach(async (to, from, next) => {
  const isLogin = uni.getStorageSync("isLogin");
  if (!isLogin) {
    uni.$store.settimereqStore.mineClearTimeReqFn();
    uni.$store.settimereqStore.ecologyClearTimeReqFn();
  }
  let url = to.url;
  // 逻辑代码
  if (checkLogin(url)) {
    if (isLogin) {
      byUrlWorkCb(
        url,
        uni.$store.settimereqStore.ecologySetTimeReqFn,
        uni.$store.settimereqStore.ecologyClearTimeReqFn
      );
      byUrlWorkCb(
        url,
        uni.$store.settimereqStore.mineSetTimeReqFn,
        uni.$store.settimereqStore.mineClearTimeReqFn
      );
    }
    next();
  }
});

uniCrazyRouter.afterEach((to, from) => {
  reflashHomePage(to);
});

uniCrazyRouter.onError((to, from) => {
  // 逻辑代码
});

export function checkLogin(url) {
  let route = routes["/" + url];
  // console.log(route, "-------------");
  const isLogin = uni.getStorageSync("isLogin");
  const userInfo = uni.getStorageSync("userInfo");

  setTableBar(url, isLogin, userInfo);
  if (route && route?.meta?.auth == true && !isLogin) {
    uni.$store.userStore.isShowLoginModal = true;
    console.log("open login modal");

    return false;
  }

  return true;
}

function setTableBar(url, isLogin, userInfo) {
  if (!isTabbarPage(url)) {
    return;
  }
  if (isLogin && userInfo) {
    uni.setTabBarItem({
      index: 3,
      text: userInfo.block_no,
    });
  } else {
    uni.setTabBarItem({
      index: 3,
      text: "游客",
    });
  }
}

function setNavTitle(to) {
  let route = routes["/" + to.url];
  let title;

  if (route && route?.meta?.title) {
    title = route?.meta?.group + "-" + route?.meta?.title;
    uni.setNavigationBarTitle({
      title: title,
    });
  }
}
